﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using JTest;
using JTest.DTO;
using JTest.DAO;
using JTest.BUS;
using System.Xml;

namespace JTest.GUI
{
    /// <summary>
    /// @Author: SonLT4
    /// @Version: 07102010
    /// </summary>
    public partial class frmPractice : Form
    {
        //Bien static cua chuong trinh
        List<QuestionDTO> questionList;//mang cac cau hoi
        static int[] answers;//mang luu cac dap an da chon
        static List<int> wrongAnswerIDs;//mang luu id cac cau tra loi sai
        static int curIndex;//Index trong mang cua cau hoi cua cau luyen tap dang hien thi tren form
        static int curAnswer;//1: A, 2: B, 3: C, 4: D. Luu lua chon chua user hoac dap an da chon cua cau hoi dang xem
        static int[] statistic;//2 bien int luu : so cau da lam, so cau dung
        static bool logFileSavedOK;//true: luu file thanh cong, nguoc lai false. Truyen tu frmSavePracticeLog
        static bool devHandle;//true: developer dang set gia tri cac radion button khong can update gia tri curAnswer, false nguoc lai
        static int Level = 0;
        QuestionDTO currentShow = new QuestionDTO();
        string selected = "";
        int curAnswerBK = -1;

        ///@nhannc
        ///
        //string tenCSDL = "";
        string noidungluyentap = "";
        //string capdo = "";
        string kieurade = "";
        string xemketqua = "";
        string message1 = "";
        string message2 = "";
        string ketthucluyentap = "";
        string message3 = "";
        string luuthongtin = "";
        string message4 = "";
        string dapandung = "";
        /// <summary>
        /// default constructor
        /// </summary>
        public frmPractice()
        {
            InitializeComponent();
        }

        private void resetStaticProperties()
        {
            questionList = null;
            answers = null;
            wrongAnswerIDs = null;
            curIndex = -1;
            curAnswer = -2;
            statistic = null;
            logFileSavedOK = false;
            devHandle = false;
        }

        /// <summary>
        /// Constructor cho man hinh luyen tap moi
        /// </summary>
        /// <param name="s">kieu SettingPracticeDTO, chua thong tin tuy chon luyen tap</param>
        public frmPractice(SettingsPractiseDTO s)
        {
            InitializeComponent();
            resetStaticProperties();
            Level = s.Level;
            //set gia tri hien thi cho cac labels thong tin
            string level = (s.Level == 1) ? "N1" : (s.Level == 2) ? "N2/N3" : (s.Level == 3) ? "N4" : "N5";
            lbCapDo.Text = level;
            lbNoiDung.Text = (s.Type == 1) ? "Từ vựng" : "Ngữ pháp";
            lbKieuRaDe.Text = (s.Mode == 0) ? "Ngẫu nhiên" : (s.Mode == 1) ? "Tuần tự" : "Làm lại câu sai";
            lbCauBatDau.Text = s.From.ToString();
            lbCauKetThuc.Text = s.To.ToString();
            lbThongKeCauDaLam.Text = "0/" + (s.To - s.From + 1);
            lbThongKeCauDung.Text = "0/0";
            lbTenCSDL.Text = s.DbName;

            //lay danh sach cau hoi cho luyen tap moi
            loadDataForNewPractice(s);
            // currentShow = questionList[0];
            currentShow.Answer = questionList[0].Answer;
            currentShow.AnswerA = questionList[0].AnswerA;
            currentShow.AnswerB = questionList[0].AnswerB;
            currentShow.AnswerC = questionList[0].AnswerC;
            currentShow.AnswerD = questionList[0].AnswerD;
            currentShow.ID = questionList[0].ID;
            currentShow.Question = questionList[0].Question;

            currentShow = command.unscrambler(currentShow);
            //set cac gia tri hien thi con lai cho form
            setControlsPropertiesForNewQuestion();
            checkQuestionAvailability();

            //set gia tri ban dau cho các check box
            cbTuDongHienKetQua.Checked = false;
            cbTuDongSangCauSau.Checked = true;

            ///@nhannc
            ///
            noidungluyentap = (s.Type == 1) ? "Từ vựng" : "Ngữ pháp";
            kieurade = (s.Mode == 0) ? "Ngẫu nhiên" : (s.Mode == 1) ? "Tuần tự" : "Làm lại câu sai";
            controlLang();
        }

        /// <summary>
        /// Constructor cho man hinh luyen tap cu
        /// , bao gom chuc nang tiep tuc va lam lai cau sai
        /// </summary>
        /// <param name="p">kieu PracticeLogDTO, chua thong tin luyen tap cu</param>
        /// <param name="flag">kieu bool, true: lam lai cau sai, false: tiep tuc luyen tap</param>
        public frmPractice(PracticeLogDTO p, bool cont)
        {
            InitializeComponent();
            resetStaticProperties();
            Level = p.SettingPractice.Level;
            //set gia tri hien thi cho cac labels thong tin
            string level = (p.SettingPractice.Level == 1) ? "N1" : (p.SettingPractice.Level == 2) ? "N2/N3" : (p.SettingPractice.Level == 3) ? "N4" : "N5";
            lbCapDo.Text = level;
            lbNoiDung.Text = (p.SettingPractice.Type == 1) ? "Từ vựng" : "Ngữ pháp";
            lbKieuRaDe.Text = (p.SettingPractice.Mode == 0) ? "Ngẫu nhiên" : (p.SettingPractice.Mode == 1) ? "Tuần tự" : "Làm lại câu sai";
            lbCauBatDau.Text = p.SettingPractice.From.ToString();
            lbCauKetThuc.Text = p.SettingPractice.To.ToString();
            lbTenCSDL.Text = p.SettingPractice.DbName;
            ///@nhannc
            ///
            noidungluyentap = (p.SettingPractice.Type == 1) ? "Từ vựng" : "Ngữ pháp";
            kieurade = (p.SettingPractice.Mode == 0) ? "Ngẫu nhiên" : (p.SettingPractice.Mode == 1) ? "Tuần tự" : "Làm lại câu sai";
            controlLang();
            //lay danh sach cau hoi cho luyen tap cu
            try
            {
                loadDataForOldPractice(p, cont);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            //hien thi thong tin cho lam tiep tuc / lam lai cau sai
            if (!cont)//neu lam lai cau sai -> xem nhu luyen tap moi voi danh sach cau sai
            {
                lbThongKeCauDaLam.Text = "0/" + (p.Statistic[0] - p.Statistic[1]);
                lbThongKeCauDung.Text = "0/0";
                statistic = new int[] { 0, 0 };
                //set gia tri hien thi cho cac controls con lai
                //currentShow = questionList[curIndex];
                currentShow.Answer = questionList[curIndex].Answer;
                currentShow.AnswerA = questionList[curIndex].AnswerA;
                currentShow.AnswerB = questionList[curIndex].AnswerB;
                currentShow.AnswerC = questionList[curIndex].AnswerC;
                currentShow.AnswerD = questionList[curIndex].AnswerD;
                currentShow.ID = questionList[curIndex].ID;
                currentShow.Question = questionList[curIndex].Question;

                currentShow = command.unscrambler(currentShow);
                setControlsPropertiesForNewQuestion();
                checkQuestionAvailability();
            }
            else//neu tiep tuc luyen tap cu
            {
                lbThongKeCauDaLam.Text = p.Statistic[0] + "/" + p.Id.Length;
                lbThongKeCauDung.Text = p.Statistic[1] + "/" + p.Statistic[0] + " (" + Math.Round(p.Statistic[1] * 1.0 / p.Statistic[0] * 100) + "%)";
                if (curIndex == questionList.Count)
                {
                    curIndex--;
                    curAnswer = answers[curIndex];
                    setControlsPropertiesForAnsweredQuestion(true);
                }
                else
                {
                    //set gia tri hien thi cho cac controls con lai
                    //currentShow = questionList[curIndex];
                    currentShow.Answer = questionList[curIndex].Answer;
                    currentShow.AnswerA = questionList[curIndex].AnswerA;
                    currentShow.AnswerB = questionList[curIndex].AnswerB;
                    currentShow.AnswerC = questionList[curIndex].AnswerC;
                    currentShow.AnswerD = questionList[curIndex].AnswerD;
                    currentShow.ID = questionList[curIndex].ID;
                    currentShow.Question = questionList[curIndex].Question;

                    currentShow = command.unscrambler(currentShow);
                    setControlsPropertiesForNewQuestion();
                }
                checkQuestionAvailability();
            }
            cbTuDongHienKetQua.Checked = true;
        }

        ///
        /// @nhannc
        /// 
        private void controlLang()
        {
            try
            {
                XmlNodeList xnList = frmMain.xml.SelectNodes("lang/luyentap");
                foreach (XmlNode xn in xnList)
                {
                    this.Text = xn["title"].InnerText;
                    gbThongTinLuyenTap.Text = xn["thongtinluyentap"].InnerText;
                    label3.Text = xn["tencsdl"].InnerText;
                    lb7.Text = xn["noidungluyentap"].InnerText;
                    if (noidungluyentap == "Từ vựng")
                        lbNoiDung.Text = xn["tuvung"].InnerText;
                    else
                        lbNoiDung.Text = xn["nguphap"].InnerText;
                    lb6.Text = xn["capdo"].InnerText;
                    lb5.Text = xn["kieurade"].InnerText;
                    if (kieurade == "Ngẫu nhiên")
                        lbKieuRaDe.Text = xn["ngaunhien"].InnerText;
                    else if (kieurade == "Tuần tự")
                        lbKieuRaDe.Text = xn["tuantu"].InnerText;
                    else
                        lbKieuRaDe.Text = xn["lamlaicaccausai"].InnerText;

                    label2.Text = xn["phamviluyentap"].InnerText;
                    lb8.Text = xn["den"].InnerText;
                    label4.Text = xn["socaudalam"].InnerText;
                    lbSoCauDung.Text = xn["socaudalam"].InnerText;
                    gbLuyenTap.Text = xn["luyentap"].InnerText;
                    lbSTTCau.Text = xn["cau"].InnerText;
                    gbChonDapAn.Text = xn["chondapan"].InnerText;
                    btXemKetQua.Text = xn["xemketqua"].InnerText;
                    cbTuDongSangCauSau.Text = xn["tudongsangcausau"].InnerText;
                    cbTuDongHienKetQua.Text = xn["tudonghienketqua"].InnerText;

                    btKetThuc.Text = xn["ketthuc"].InnerText;
                    message1 = xn["message1"].InnerText;
                    message2 = xn["message2"].InnerText;
                    message3 = xn["message3"].InnerText;
                    message4 = xn["message4"].InnerText;
                    xemketqua = xn["xemketqua"].InnerText;
                    ketthucluyentap = xn["ketthucluyentap"].InnerText;
                    luuthongtin = xn["luuthongtinluyentap"].InnerText;
                    dapandung = xn["dapandung"].InnerText;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);            
            }
        }
        /// <summary>
        /// Ham load du lieu cho man hinh luyen tap cu
        /// </summary>
        /// <param name="p">kieu PracticeDTO, chua thong tin luyen tap cu</param>
        /// <param name="flag">kieu bool, true: lam lai cau sai, false: tiep tuc</param>
        private void loadDataForOldPractice(PracticeLogDTO p, bool cont)
        {
            try
            {
                wrongAnswerIDs = new List<int>();
                if (!cont)//neu lam lai cau sai -> xem nhu luyen tap moi
                {
                    //lay danh sach cau hoi sai
                    questionList = PracticeBUS.getQuestionsFromIDsList(p.WrongAnswerIDs, p.SettingPractice);
                    //load danh sach id cac cau tra loi sai
                    answers = new int[p.WrongAnswerIDs.Length];
                    for (int i = 0; i < answers.Length; i++)
                    {
                        answers[i] = -1;
                    }
                    curIndex = 0;//bat dau tu cau hoi dau tien  
                }
                else//tiep tuc luyen tap cu
                {
                    //lay danh sach cau hoi luyen tap cu
                    if (p.SettingPractice.Mode != 1)
                    {
                       
                       questionList = PracticeBUS.getQuestionsFromIDsList(p.Id,p.SettingPractice);
                    }
                    else
                    {
                        questionList = PracticeBUS.getQuestionListInSuccessionOrder(p.SettingPractice);
                    }
                    //copy danh sach ids cau tra loi sai sang data cua man hinh
                    answers = (int[])p.Answers.Clone();
                    for (int i = 0; i < p.WrongAnswerIDs.Length; i++)
                    {
                        wrongAnswerIDs.Add(p.WrongAnswerIDs[i]);
                    }
                    //lay id cau hoi chua lam dau tien trong danh sach
                    for (curIndex = 0; curIndex < answers.Length; curIndex++)
                    {
                        if (answers[curIndex] == -1)
                        {
                            break;
                        }
                    }
                }
                //copy thong tin thong ke cua lan luyen tap cu
                statistic = (int[])p.Statistic.Clone();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Ham load du lieu cho man hinh luyen tap moi
        /// </summary>
        /// <param name="s">kieu SettingPracticeDTO, chua thong tin tuy chon luyen tap</param>
        private void loadDataForNewPractice(SettingsPractiseDTO s)
        {
            string tableType = (s.Type == 1) ? "vocabulary" : "grammar";

            try
            {
                if (s.Mode == 0)//Ngau nhien
                {
                    questionList = PracticeBUS.getQuestionListInRandomOrder(s.From, s.To, s.Level, tableType);
                }
                else//Tuan tu
                {
                    questionList = PracticeBUS.getQuestionListInSuccessionOrder(s.From, s.To, s.Level, tableType);
                }
                answers = new int[s.To - s.From + 1];
                for (int i = 0; i < answers.Length; i++)
                {
                    answers[i] = -1;
                }
                wrongAnswerIDs = new List<int>();
                curIndex = 0;
                statistic = new int[] { 0, 0 };
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        /// <summary>
        /// Ham kiem tra da toi dau hoac cuoi danh sach cau hoi chua.
        /// Neu da den dau hoac cuoi danh sach, set lai thuoc tinh cho 2 button next + previous
        /// </summary>
        private void checkQuestionAvailability()
        {
            if (curIndex == 0)
            {
                btPrevious.Enabled = false;
            }
            else
            {
                btPrevious.Enabled = true;
            }
            if (curIndex == questionList.Count - 1)
            {
                btNext.Enabled = false;
            }
            else
            {
                btNext.Enabled = true;
            }
        }

        /// <summary>
        /// Ham set thuoc tinh cho cac controls lien quan, 
        /// khi man hinh can hien thi thong tin cho mot cau hoi chua lam
        /// </summary>
        private void setControlsPropertiesForNewQuestion()
        {
            devHandle = true;
            rbDapAnA.Checked = false;
            rbDapAnB.Checked = false;
            rbDapAnC.Checked = false;
            rbDapAnD.Checked = false;
            devHandle = false;
            rbDapAnA.Enabled = true;
            rbDapAnB.Enabled = true;
            rbDapAnC.Enabled = true;
            rbDapAnD.Enabled = true;
            btXemKetQua.Enabled = true;
            lbDapAnDung.Text = "";
            lbDapAnDungValue.Text = "";
            //rtbCauHoi.Text = " 問い: " + questionList[curIndex].Question + "\r\n\r\n" + 
            //                 " A. " + questionList[curIndex].AnswerA + "\r\n" + 
            //                 " B. " + questionList[curIndex].AnswerB + "\r\n" + 
            //                 " C. " + questionList[curIndex].AnswerC + "\r\n" + 
            //                 " D. " +questionList[curIndex].AnswerD;

            rtbCauHoi.Text = " 問い: " + currentShow.Question + "\r\n\r\n" +
                          " A. " + currentShow.AnswerA + "\r\n" +
                          " B. " + currentShow.AnswerB + "\r\n" +
                          " C. " + currentShow.AnswerC + "\r\n" +
                          " D. " + currentShow.AnswerD;
            lbSocau.Text = questionList[curIndex].ID + " (" + (curIndex + 1) + "/" + questionList.Count + ")";
            curAnswer = -1;
            pbKetQua.Image = Properties.Resources.question;
        }

        /// <summary>
        /// Ham set thuoc tinh cac controls lien quan,
        /// khi man hinh can hien thi 
        /// </summary>
        private void setControlsPropertiesForAnsweredQuestion(bool b)
        {
            rbDapAnA.Enabled = false;
            rbDapAnB.Enabled = false;
            rbDapAnC.Enabled = false;
            rbDapAnD.Enabled = false;
            if (b)
            {
                devHandle = true;
                switch (curAnswer)
                {
                    case 1:
                        rbDapAnA.Checked = true;
                        break;
                    case 2:
                        rbDapAnB.Checked = true;
                        break;
                    case 3:
                        rbDapAnC.Checked = true;
                        break;
                    case 4:
                        rbDapAnD.Checked = true;
                        break;
                    default:
                        rbDapAnA.Checked = false;
                        rbDapAnB.Checked = false;
                        rbDapAnC.Checked = false;
                        rbDapAnD.Checked = false;
                        break;
                }
                devHandle = false;
                rtbCauHoi.Text = " 問い: " + questionList[curIndex].Question + "\r\n\r\n" +
                                 " A. " + questionList[curIndex].AnswerA + "\r\n" +
                                 " B. " + questionList[curIndex].AnswerB + "\r\n" +
                                 " C. " + questionList[curIndex].AnswerC + "\r\n" +
                                 " D. " + questionList[curIndex].AnswerD;
                lbDapAnDungValue.Text = questionList[curIndex].Answer.ToString();
            }
            else
            {
                string dapan = "";
                if (questionList[curIndex].Answer.ToString() == "A")
                {
                    dapan = questionList[curIndex].AnswerA;
                }
                else if (questionList[curIndex].Answer.ToString() == "B")
                {
                    dapan = questionList[curIndex].AnswerB;
                }
                else if (questionList[curIndex].Answer.ToString() == "C")
                {
                    dapan = questionList[curIndex].AnswerC;
                }
                else 
                {
                    dapan = questionList[curIndex].AnswerD;
                }

                if (dapan == currentShow.AnswerA)
                    dapan = "A";
                else if (dapan == currentShow.AnswerB)
                    dapan = "B";
                else if (dapan == currentShow.AnswerC)
                    dapan = "C";
                else
                    dapan = "D";
                lbDapAnDungValue.Text = dapan;
                //lbDapAnDungValue.Text = questionList[curIndex].Answer.ToString();
            }
            btXemKetQua.Enabled = false;

            if (curAnswer == convertToIntValue(questionList[curIndex].Answer.ToString()))
            {
                lbDapAnDungValue.ForeColor = Color.Blue;
                pbKetQua.Image = Properties.Resources.thumbs_up;
            }
            else
            {
                lbDapAnDungValue.ForeColor = Color.Red;
                pbKetQua.Image = Properties.Resources.thumbs_down;
            }
            answers[curIndex] = curAnswer;
            //rtbCauHoi.Text = " 問い: " + questionList[curIndex].Question + "\r\n\r\n" +
            //                 " A. " + questionList[curIndex].AnswerA + "\r\n" +
            //                 " B. " + questionList[curIndex].AnswerB + "\r\n" +
            //                 " C. " + questionList[curIndex].AnswerC + "\r\n" +
            //                 " D. " + questionList[curIndex].AnswerD;
            lbSocau.Text = questionList[curIndex].ID + " (" + (curIndex + 1) + "/" + questionList.Count + ")";
            lbDapAnDung.Text = dapandung;
           
        }

        /// <summary>
        /// Ham chuyen gia tri string cua dap an
        /// sang gia tri int tuong ung
        /// A: 1, B: 2, C: 3, D:4
        /// </summary>
        /// <param name="answer">kieu string, chua dap an</param>
        /// <returns>kieu int, gia tri int tuong ung cua dap an</returns>
        private int convertToIntValue(string answer)
        {
            return (answer.CompareTo("A") == 0) ? 1 : (answer.CompareTo("B") == 0) ? 2 : (answer.CompareTo("C") == 0) ? 3 : 4;
        }

        /// <summary>
        /// 
        /// </summary>
        private void updateStatistic()
        {
            statistic[0]++;
            int temp = convertToIntValue(questionList[curIndex].Answer.ToString());
            if (curAnswer == temp)
            {
                statistic[1]++;
            }
            else
            {
                wrongAnswerIDs.Add(questionList[curIndex].ID);//luu id vao danh sach cau sai
            }
            lbThongKeCauDaLam.Text = statistic[0] + "/" + questionList.Count;
            lbThongKeCauDung.Text = statistic[1] + "/" + statistic[0] + " (" + Math.Round(statistic[1] * 1.0 / statistic[0] * 100) + "%)";
        }

        /// <summary>
        /// Ham xu ly su kien user click vao button Xem Ket Qua.
        /// Khi user muon xem dap an dung va cham cau tra loi cho cau hoi hien tai
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btXemKetQua_Click(object sender, EventArgs e)
        {
            //luu lai lua chon cua user
            answers[curIndex] = curAnswer;
            if (answers[curIndex] == -1)
            {
                //truong hop user chua cho dap an, nhung van muon xem dap an dung cho cau hoi
                //hien thong bao confirm, va xem nhu cau tra loi cua user cho cau hoi nay la sai
                DialogResult id = MessageBox.Show(message1,
                    xemketqua + " ?", MessageBoxButtons.OKCancel);
                if (id == DialogResult.OK)
                {
                    answers[curIndex] = curAnswer = 0;
                    //hien thi dap an dung
                    setControlsPropertiesForAnsweredQuestion(false);
                }
                else { return; }
            }
            else//neu user da chon dap an
            {
                //hien thi dap an dung
                setControlsPropertiesForAnsweredQuestion(false);
            }
            //update info thong ke
            updateStatistic();

            // ToanNN
            // sang câu sau nếu câu trả lời là đúng và cbTuDongSangCauSau được chọn
            if ((curAnswer == convertToIntValue(questionList[curIndex].Answer.ToString())) && cbTuDongSangCauSau.Checked)
            {
                btNext_Click(sender, e);
            }

        }

        /// <summary>
        /// Ham xu ly su kien user click button Next.
        /// Khi user muon xem cau hoi tiep theo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btNext_Click(object sender, EventArgs e)
        {
            if (curIndex < questionList.Count - 1)
            {
                if (curAnswer == -1)//neu user chua tra loi cau hoi hien tai
                {
                    //truong hop user chua chon dap an, nhung van muon xem dap an dung cho cau hoi
                    //hien thong bao confirm, va xem nhu cau tra loi cua user cho cau hoi nay la sai
                    DialogResult id = MessageBox.Show(message2,
                        xemketqua + " ?", MessageBoxButtons.OK);
                    if (id == DialogResult.OK)
                    {
                    //    answers[curIndex] = 0;//gan gia tri dap an la "chua tra loi"
                    //    updateStatistic();//cap nhat thong ke
                    //    curIndex++;//tang index
                    //    curAnswer = answers[curIndex];
                    //    checkQuestionAvailability();
                    //    //currentShow = questionList[curIndex];
                    //    currentShow.Answer = questionList[curIndex].Answer;
                    //    currentShow.AnswerA = questionList[curIndex].AnswerA;
                    //    currentShow.AnswerB = questionList[curIndex].AnswerB;
                    //    currentShow.AnswerC = questionList[curIndex].AnswerC;
                    //    currentShow.AnswerD = questionList[curIndex].AnswerD;
                    //    currentShow.ID = questionList[curIndex].ID;
                    //    currentShow.Question = questionList[curIndex].Question;

                    //    currentShow = command.unscrambler(currentShow);
                    //    setControlsPropertiesForNewQuestion();
                        return;
                    }
                    else { return; }
                }
                else//neu cau hoi hien tai da duoc chon dap an
                {
                    if (answers[curIndex + 1] == -1)//neu cau tiep theo la cau chua lam
                    {
                        if (answers[curIndex] == -1)//neu cau hien tai la cau chua lam
                        {
                            answers[curIndex] = curAnswer;//luu lua chon cua user
                            updateStatistic();//cap nhat thong ke
                        }
                        curIndex++;//tang index len 1
                        curAnswer = answers[curIndex];//set lai gia tri lua chon cho cau tiep theo
                        checkQuestionAvailability();//kiem tra danh sach cau hoi
                        //currentShow = questionList[curIndex];
                        currentShow.Answer = questionList[curIndex].Answer;
                        currentShow.AnswerA = questionList[curIndex].AnswerA;
                        currentShow.AnswerB = questionList[curIndex].AnswerB;
                        currentShow.AnswerC = questionList[curIndex].AnswerC;
                        currentShow.AnswerD = questionList[curIndex].AnswerD;
                        currentShow.ID = questionList[curIndex].ID;
                        currentShow.Question = questionList[curIndex].Question;

                        currentShow = command.unscrambler(currentShow);
                        setControlsPropertiesForNewQuestion();//hien thi cau hoi moi   
                    }
                    else//neu cau tiep theo la cau da lam
                    {
                        curIndex++;//tang index
                        checkQuestionAvailability();//kiem tra danh sach cau hoi
                        curAnswer = answers[curIndex];//set lai gia tri dap an
                        setControlsPropertiesForAnsweredQuestion(true);//hien thi cau hoi cu~
                    }
                }
            }
        }

        /// <summary>
        /// Ham xu ly su kien user click button Previous.
        /// Khi user muon xem cau hoi truoc do
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btPrevious_Click(object sender, EventArgs e)
        {
            curIndex--;
            curAnswer = answers[curIndex];
            checkQuestionAvailability();

            //hien noi dung cau hoi
            setControlsPropertiesForAnsweredQuestion(true);
        }

        /// <summary>
        /// Ham xu ly su kien user check vao rbDapAnA
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbDapAnA_CheckedChanged(object sender, EventArgs e)
        {
            if (!devHandle && rbDapAnA.Checked == true)
            {
                //
                curAnswerBK = 1;
                selected = currentShow.AnswerA;
                if (selected.CompareTo(questionList[curIndex].AnswerA) == 0)
                    curAnswer = 1;
                else if (selected.CompareTo(questionList[curIndex].AnswerB) == 0)
                    curAnswer = 2;
                else if (selected.CompareTo(questionList[curIndex].AnswerC) == 0)
                    curAnswer = 3;
                else
                    curAnswer = 4;
                // ToanNN
                // xử lý cho các checkbox.
                if (cbTuDongSangCauSau.Checked || cbTuDongHienKetQua.Checked)
                {
                    //if (cbTuDongHienKetQua.Checked == true) //code cũ
                    btXemKetQua_Click(sender, e);
                }
            }
        }
        /// <summary>
        /// Ham xu ly su kien user check vao rbDapAnB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbDapAnB_CheckedChanged(object sender, EventArgs e)
        {
            if (!devHandle && rbDapAnB.Checked == true)
            {
                //
                curAnswerBK = 2;
                selected = currentShow.AnswerB;
                if (selected.CompareTo(questionList[curIndex].AnswerA) == 0)
                    curAnswer = 1;
                else if (selected.CompareTo(questionList[curIndex].AnswerB) == 0)
                    curAnswer = 2;
                else if (selected.CompareTo(questionList[curIndex].AnswerC) == 0)
                    curAnswer = 3;
                else
                    curAnswer = 4;

                // ToanNN
                // xử lý cho các checkbox.
                if (cbTuDongSangCauSau.Checked || cbTuDongHienKetQua.Checked)
                {
                    btXemKetQua_Click(sender, e);
                }
            }
        }

        /// <summary>
        /// Ham xu ly su kien user check vao rbDapAnC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbDapAnC_CheckedChanged(object sender, EventArgs e)
        {
            if (!devHandle && rbDapAnC.Checked == true)
            {
                //
                curAnswerBK = 3;
                selected = currentShow.AnswerC;
                if (selected.CompareTo(questionList[curIndex].AnswerA) == 0)
                    curAnswer = 1;
                else if (selected.CompareTo(questionList[curIndex].AnswerB) == 0)
                    curAnswer = 2;
                else if (selected.CompareTo(questionList[curIndex].AnswerC) == 0)
                    curAnswer = 3;
                else
                    curAnswer = 4;

                // ToanNN
                // xử lý cho các checkbox.
                if (cbTuDongSangCauSau.Checked || cbTuDongHienKetQua.Checked)
                {
                    //if (cbTuDongHienKetQua.Checked == true) //code cũ
                    btXemKetQua_Click(sender, e);
                }
            }
        }

        /// <summary>
        /// Ham xu ly su kien user check vao rbDapAnD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbDapAnD_CheckedChanged(object sender, EventArgs e)
        {
            if (!devHandle && rbDapAnD.Checked == true)
            {
                //
                curAnswerBK = 4;
                selected = currentShow.AnswerD;
                if (selected.CompareTo(questionList[curIndex].AnswerA) == 0)
                    curAnswer = 1;
                else if (selected.CompareTo(questionList[curIndex].AnswerB) == 0)
                    curAnswer = 2;
                else if (selected.CompareTo(questionList[curIndex].AnswerC) == 0)
                    curAnswer = 3;
                else
                    curAnswer = 4;

                // ToanNN
                // xử lý cho các checkbox.
                if (cbTuDongSangCauSau.Checked || cbTuDongHienKetQua.Checked)
                {
                    //if (cbTuDongHienKetQua.Checked == true) //code cũ
                    btXemKetQua_Click(sender, e);
                }
            }
        }

        /// <summary>
        /// Ham xu ly su kien user click button Ket Thuc
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btKetThuc_Click(object sender, EventArgs e)
        {
            //Hien thi message box xac nhan ket thuc luyen tap
            DialogResult dr = MessageBox.Show(message3, ketthucluyentap, MessageBoxButtons.YesNoCancel);
            //Thuc hien theo option user chon 
            if (dr == DialogResult.Yes)//luu ket qua luyen tap
            {
                if (curAnswer != -1 && btXemKetQua.Enabled == true)
                {
                    answers[curIndex] = curAnswer;
                    updateStatistic();
                }
                frmSavePracticeLog k = new frmSavePracticeLog(createLogForSave(), this);
                k.ShowDialog(this);
            }
            else
            {
                if (dr == DialogResult.No)//khong luu ket qua luyen tap
                {
                    logFileSavedOK = true;
                    this.Dispose();
                }
                //else
                //{
                //  Huy thao tac luu -> khong lam gi ca
                //}
            }
        }

        /// <summary>
        /// Ham gui message close form Luyen Tap
        /// </summary>
        public void closeThisForm(bool b)
        {
            logFileSavedOK = b;
            if (b)
            {
                MessageBox.Show(message4, luuthongtin);
                this.Dispose();
            }
            else
            {
                if (btXemKetQua.Enabled == true)
                {
                    answers[curIndex] = -1;
                }
            }
        }

        /// <summary>
        /// Ham bat su kien user muon tat man hinh luyen tap
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frLuyenTap_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!logFileSavedOK)
            {
                e.Cancel = true;
                btKetThuc_Click(sender, e);
                if (logFileSavedOK)
                {
                    e.Cancel = false;
                }
            }
        }

        /// <summary>
        /// Ham tao CTDL PracticeLogDTO tu du lieu cua man hinh luyen tap
        /// de luu ra file log hoac file excel
        /// </summary>
        /// <returns>kieu PraticeLogDTO, chua thong tin luyen tap hien tai</returns>
        private PracticeLogDTO createLogForSave()
        {
            PracticeLogDTO p = new PracticeLogDTO();
            p.SettingPractice = new SettingsPractiseDTO();
            p.SettingPractice.DbName = lbTenCSDL.Text;
            p.SettingPractice.From = Int32.Parse(lbCauBatDau.Text);
            p.SettingPractice.To = Int32.Parse(lbCauKetThuc.Text);
            p.SettingPractice.Type = (noidungluyentap.CompareTo("Từ vựng") == 0) ? 1 : 2;
            p.SettingPractice.Level = (lbCapDo.Text.CompareTo("N1") == 0) ? 1 : (lbCapDo.Text.CompareTo("N2/N3") == 0) ? 2 : (lbCapDo.Text.CompareTo("N4") == 0) ? 3 : 4;
            p.SettingPractice.Mode = (kieurade.CompareTo("Ngẫu nhiên") == 0) ? 0 : (kieurade.CompareTo("Tuần tự") == 1) ? 1 : 2;

            p.Answers = (int[])answers.Clone();
            p.Id = new int[questionList.Count];
            for (int i = 0; i < p.Id.Length; i++)
            {
                p.Id[i] = questionList[i].ID;
            }
            p.Statistic = (int[])statistic.Clone();
            if (wrongAnswerIDs.Count == 0)
            {
                p.WrongAnswerIDs = new int[] { 0 };
            }
            else
            {
                p.WrongAnswerIDs = new int[wrongAnswerIDs.Count];
                for (int i = 0; i < p.WrongAnswerIDs.Length; i++)
                {
                    p.WrongAnswerIDs[i] = wrongAnswerIDs[i];
                }
            }
            return p;
        }

        // ToanNN
        /// <summary>
        /// xử lý khi thay đổi tình trạng cbToDongHienKetQua
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbTuDongHienKetQua_CheckedChanged(object sender, EventArgs e)
        {
            if (cbTuDongHienKetQua.Checked)
            {
                // reset lại đáp án để user chọn.
                rbDapAnA.Checked = false;
                rbDapAnB.Checked = false;
                rbDapAnC.Checked = false;
                rbDapAnD.Checked = false;
            }
        }

        // ToanNN
        /// <summary>
        /// xử lý khi thay đổi tình trang cbTuDongSangCauSau. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbTuDongSangCauSau_CheckStateChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbTuDongSangCauSau.Checked == false)
                {
                    cbTuDongHienKetQua.Enabled = true;
                    cbTuDongHienKetQua.Checked = true;
                }
                else
                {
                    cbTuDongHienKetQua.Enabled = false;
                    cbTuDongHienKetQua.Checked = false;
                }

                // reset lại đáp án để user chọn.
                rbDapAnA.Checked = false;
                rbDapAnB.Checked = false;
                rbDapAnC.Checked = false;
                rbDapAnD.Checked = false;
            }
            catch { }
        }


    }
}
